# -*- coding = utf-8 -*-
# @Time : 2021/11/1 16:56
# @Author : 刘纹石
# @File : Fight_Enemies.py
# @Software : PyCharm
# BOSS值
import math
from time import sleep

import pygame.image
import Allcard
import PublicTools
import random
import matplotlib.pyplot as plt

BOSS_weight = {1: 10, 2: 100, 3: 200}  # boss的血量
Function = []  # 所有卡牌
Chosen_function = []  # 选中的卡牌


def formula2img(str_latex, out_file, img_size=(5, 3), font_size=16):
    fig = plt.figure(figsize=img_size)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.text(0.5, 0.5, str_latex, fontsize=font_size, verticalalignment='center', horizontalalignment='center')
    plt.savefig(out_file)


def Sci_Str(n):
    i = 0
    string = ""
    if n != 0:
        if n > 1:
            n = round(n, 3)
            string = str(n)
        else:
            while n < 1:
                i -= 1
                n *= 10
            n = round(n, 3)
            string = str(n)
            string = string + "E" + str(i)
    return string


class function:
    def __init__(self, weight):
        self.x_3 = 0
        self.x_2 = 0
        self.x = 0
        self.divide = 0
        self.add = 0
        self.slt = 0
        self.ex = 0
        self.sinx = 0
        self.cosx = 0
        self.level = 0  # 关卡的等级
        self.output = 0  # 没有限制当前函数组合的伤害或者治疗量
        self.max = 0  # 一次攻击击杀的最大血量
        self.weight = weight  # 权重
        self.target = 0  # 使用对象
        self.name = ""
        self.ran = {"x_3": 5, "x_2": 10, "x": 40, "divide": 40, "add": 100, "slt": 100, "ex": 2, "sinx": 20, "cosx": 20}

    def ran_level(self):
        # 计算各个系数出现频率，当随机数小于对应数字即取1，否则取0；频率随关卡等级提升而提升
        from Main import chosen_mission
        self.level = chosen_mission - 1
        self.ran["x_3"] = self.ran["x_3"] + self.level * 1
        self.ran["x_2"] = self.ran["x_2"] + self.level * 1
        self.ran["x"] = self.ran["x"] + self.level * 5
        self.ran["divide"] = self.ran["divide"] + self.level * 5
        self.ran["ex"] = self.ran["ex"] + self.level * 1
        self.ran["sinx"] = self.ran["sinx"] + self.level * 5
        self.ran["cosx"] = self.ran["cosx"] + self.level * 5
        print("this is a function")

    def n_level(self):
        self.level = random.randint(0, 99)
        if self.level < self.ran["x_3"]:
            self.x_3 = (self.level % 2) / 200  # x的三次方

        self.level = random.randint(0, 99)
        if self.level < self.ran["x_2"]:
            self.x_2 = (self.level % 3 + random.random()) / 1  # x的平方

        self.level = random.randint(0, 99)
        if self.level < self.ran["x"]:
            self.x = self.level % 4 + random.random()  # 乘法

        self.level = random.randint(0, 99)
        if self.level < self.ran["divide"]:
            self.divide = self.level % 10 + random.random()  # 除法

        self.level = random.randint(0, 99)
        while self.level == 0:
            self.level = random.randint(0, 99)
        self.add = self.level % 10 + random.random()  # 加法

        self.level = random.randint(0, 99)
        while self.level == 0:
            self.level = random.randint(0, 99)
        self.slt = self.level % 10 + random.random()  # 减法

        self.level = random.randint(0, 99)
        if self.level < self.ran["ex"]:
            self.ex = random.random()  # ex

        self.level = random.randint(0, 99)
        if self.level < self.ran["sinx"]:
            self.sinx = self.level % 10 + random.random()  # sinx

        self.level = random.randint(0, 99)
        if self.level < self.ran["cosx"]:
            self.cosx = self.level % 10 + random.random()  # cosx

    def max_loss(self):
        # 确定一张卡牌一次能够造成最大伤害的占比
        self.level = random.randint(0, 1000)
        if self.level == 1000:  # 千分之一概率秒杀
            self.max = self.weight
        elif 990 <= self.level < 1000:
            self.max = self.weight / 2
        elif 940 <= self.level < 990:
            self.max = round(self.weight / 3, 3)
        else:
            self.max = round(self.weight / 10, 3)

    def reduce(self):
        # 调整系数使得一次造成的伤害最大为max
        self.output += self.weight **3 * self.x_3
        self.output += self.weight * self.weight * self.x_2
        self.output += self.weight * self.x
        if self.divide != 0:
            self.output += self.weight / self.divide
        self.output += self.add
        self.output -= self.slt
        self.output += math.sin(self.weight) * self.sinx
        self.output += math.cos(self.weight) * self.cosx
        self.output += round(math.pi ** self.weight * self.ex, 3)  # 计算当前系数之下相加结果
        while self.output > self.max:  # 如果当前结果大于一次函数所能造成的最大伤害则调整系数
            self.x_3 = self.x_3 * self.max / self.output
            self.x_2 = self.x_2 * self.max / self.output
            self.x = self.x * self.max / self.output
            self.divide = self.divide * self.max / self.output
            self.add = self.add * self.max / self.output
            self.slt = self.slt * self.max / self.output
            self.sinx = self.sinx * self.max / self.output
            self.cosx = self.cosx * self.max / self.output
            self.ex = self.ex * self.max / self.output
            self.output = 0
            self.output += self.weight * self.weight * self.weight * self.x_3
            self.output += self.weight * self.weight * self.x_2
            self.output += self.weight * self.x
            if self.divide != 0:
                self.output += self.weight / self.divide
            self.output += self.add
            self.output -= self.slt
            self.output += math.sin(self.weight) * self.sinx
            self.output += math.cos(self.weight) * self.cosx
            self.output += round(math.pi ** self.weight * self.ex, 3)

    def name_get(self):
        self.name = "x + "
        if self.x_3 != 0:
            self.name = self.name + Sci_Str(self.x_3) + "*x^3 + "
        if self.x_2 != 0:
            self.name = self.name + Sci_Str(self.x_2) + "*x^2 + "
        if self.x != 0:
            self.name = self.name + Sci_Str(self.x) + "*x + "
        if self.divide != 0:
            self.name = self.name + "x/" + Sci_Str(self.divide) + " + "
        if self.sinx != 0:
            self.name = self.name + Sci_Str(self.sinx) + "*sinx + "
        if self.cosx != 0:
            self.name = self.name + Sci_Str(self.cosx) + "*cosx + "
        if self.ex != 0:
            self.name = self.name + Sci_Str(self.ex) + "*e^" + str(self.weight) + " + "
        self.name += Sci_Str(self.add) + " - " + Sci_Str(self.slt)


class Combat:
    def __init__(self, n):
        from Main import user
        self.usercombat = user.weight
        self.enemy = n
        self.order = 0
        self.keep = 1
        self.show = 0
        self.choose_number = 0  # 当前已经选择的卡牌数量
        self.chosen = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
        self.position = {0: (10, 75), 1: (170, 75), 2: (330, 75), 3: (490, 75), 4: (650, 75)}
        self.word = {0: (30, 165), 1: (190, 165), 2: (350, 165), 3: (510, 165), 4: (170, 165)}

    def card_function(self):
        print("this is a function")

ct=[0,0,0,0,0,0]
ca=[0,0,0,0,0,0]
def randcard():
    for i in range(6):
        cardtype = random.randint(0, 4)
        a = random.randint(1, 8)
        ct[i]=cardtype
        ca[i]=a
        if cardtype == 0:
            str_latex = '$x+' + str(a) + '$'
            formula2img(str_latex, '../Docs/images/f' + str(i) + '.png', img_size=(3, 2), font_size=64)
        elif cardtype == 1:
            str_latex = '$' + str(a) + 'x$'
            formula2img(str_latex, '../Docs/images/f' + str(i) + '.png', img_size=(3, 2), font_size=64)
        elif cardtype == 2:
            str_latex = '$' + str(a) + 'x^2$'
            formula2img(str_latex, '../Docs/images/f' + str(i) + '.png', img_size=(3, 2), font_size=64)
        elif cardtype == 3:
            str_latex = '$' + str(a) + 'x^3$'
            formula2img(str_latex, '../Docs/images/f' + str(i) + '.png', img_size=(3, 2), font_size=64)

def chosecard(word,i):
    if ct[i]==0:
        word=word+'+'+str(ca[i])
    elif ct[i]==1:
        word=str(ca[i])+'*('+word+')'
    elif ct[i]==2:
        word=str(ca[i])+'*('+word+')**2'
    elif ct[i]==3:
        word=str(ca[i])+'*('+word+')**3'
    return word

def fight():
    from Main import chosen_mission
    print("这是战斗界面", 1)
    combat = Combat(BOSS_weight[1])

    # 战斗背景

    # 血槽显示
    weight_size = (150, 50)
    user_location = (320, 10)
    boss_location = (320, 390)

    card_size = (150, 250)
    Every_F = function(0)
    nnext = 1
    bossblood=10000
    myblood=5000
    chosen=0
    final = "x"
    win=0
    # 战斗过程
    while combat.keep:
        import Main
        background = pygame.image.load("../Docs/images/combat.jpg")
        if(bossblood<=0):
            win=1
            break
        Main.screen.blit(pygame.transform.scale(background, (1120, 630)), (0, 0))
        pygame.draw.rect(Main.screen, (255, 0, 0), (175, 50, bossblood/20, 20), 0)
        pygame.draw.rect(Main.screen, (255, 0, 0), (175, 580, myblood / 20, 20), 0)
        boss = pygame.image.load("../Docs/images/boss2.png")
        boss = pygame.transform.scale(boss, (150, 150))
        font = pygame.font.Font("../Docs/images/SourceHanSerif-Light.ttc", 15)
        text1 = font.render(str(bossblood), True, (0, 0, 0))
        Main.screen.blit(text1, (175,20))
        text2 = font.render(str(myblood), True, (0, 0, 0))
        Main.screen.blit(text2, (175, 600))
        text3 = font.render("技能：30%概率无效你的卡牌", True, (0, 0, 0))
        text4 = font.render("log之盾：将你卡牌中所有幂变为常数", True, (0, 0, 0),(255,165,0))
        Main.screen.blit(text3, (860, 20))
        Main.screen.blit(text4, (860, 40))
        Main.screen.blit(boss, (20, 20))
        button_size=(100,120)
        button_y=450
        if nnext == 1:
            randcard()
            nnext=0
        (x, y) = pygame.mouse.get_pos()
        if (x > 200) & (x < 200 + button_size[0]) & (y > button_y) & (y < button_y + button_size[1]):
            if PublicTools.button((200, button_y), button_size, "", 18, (410, 180), "../Docs/images/f1.png"):
                final=chosecard(final,1)
                chosen+=1
        else:
            PublicTools.button((200, button_y), button_size, "", 18, (410, 180), "../Docs/images/card.jpg")
        if (x > 355) & (x < 355 + button_size[0]) & (y > button_y) & (y < button_y + button_size[1]):
            if PublicTools.button((355, button_y), button_size, "", 18, (410, 180), "../Docs/images/f2.png"):
                final=chosecard(final,2)
                chosen += 1
        else:
            PublicTools.button((355, button_y), button_size, "", 18, (410, 180), "../Docs/images/card.jpg")
        if (x > 510) & (x < 510 + button_size[0]) & (y > button_y) & (y < button_y + button_size[1]):
            if PublicTools.button((510, button_y), button_size, "", 18, (410, 180), "../Docs/images/f3.png"):
                final=chosecard(final,3)
                chosen += 1
        else:
            PublicTools.button((510, button_y), button_size, "", 18, (410, 180), "../Docs/images/card.jpg")
        if (x > 665) & (x < 665 + button_size[0]) & (y > button_y) & (y < button_y + button_size[1]):
            if PublicTools.button((665, button_y), button_size, "", 18, (410, 180), "../Docs/images/f4.png"):
                final=chosecard(final,4)
                chosen += 1
        else:
            PublicTools.button((665, button_y), button_size, "", 18, (410, 180), "../Docs/images/card.jpg")
        if (x > 820) & (x < 820 + button_size[0]) & (y > button_y) & (y < button_y + button_size[1]):
            if PublicTools.button((820, button_y), button_size, "", 18, (410, 180), "../Docs/images/f5.png"):
                final=chosecard(final,5)
                chosen += 1
        else:
            PublicTools.button((820, button_y), button_size, "", 18, (410, 180), "../Docs/images/card.jpg")

        if(final!='x'):
            final1='$'+final+'$'
            formula2img(final1, '../Docs/images/f.png', img_size=(chosen*3, 2), font_size=64)
            c = pygame.image.load("../Docs/images/f.png")
            c = pygame.transform.scale(c, (chosen*100, 100))
            Main.screen.blit(c, (100, 200))
        if chosen==3:
            a=final.replace('x',str(Main.user.weight))
            print(a)
            print(eval(a))
            bossblood-=eval(a)
            final='x'
            chosen=0
            nnext=1
            myblood-=random.randint(100,300)


        # str_latex = r'$10^x$'
        # formula2img(str_latex, r'../Docs/images/f1.png', img_size=(3, 2), font_size=64)
        # if PublicTools.button(boss_location, weight_size, str(combat.enemy), 14, (380, 25), "../Docs/images/button.png"):
        #     return 3
        # if PublicTools.button(user_location, weight_size, str(combat.usercombat), 14, (380, 405), "../Docs/images/button.png"):
        #     return 3
        # i = 0
        # if combat.show == 0:
        #     # 每次重新抽取卡牌
        #     combat.choose_number = 0
        #     combat.show = 1
        #     del Function[:]
        #     del Chosen_function[:]
        #     while i < 5:
        #         combat.chosen[i] = 0
        #         Every_F = function(combat.enemy)
        #         Every_F.ran_level()
        #         Every_F.n_level()
        #         Every_F.max_loss()
        #         Every_F.reduce()
        #         Every_F.name_get()
        #         print(Every_F.name)
        #         Function.append(Every_F)
        #         i += 1
        # i = 0
        # while i < 5:
        #     if PublicTools.button(combat.position[i], card_size, Function[0].name, 14, combat.word[i], "../Docs/images/button.png"):
        #         if combat.choose_number < 3 and combat.chosen[i] == 0:
        #             Chosen_function.append(Function[i])
        #             combat.choose_number += 1
        #             combat.chosen[1] = 1
        #     i += 1
        # if combat.choose_number == 3:
        #     combat.enemy -= Chosen_function[0].output
        #     combat.enemy -= Chosen_function[1].output
        #     combat.enemy -= Chosen_function[2].output
        #     combat.show = 0
        #     combat.chosen[0] = 0
        #     combat.chosen[1] = 0
        #     combat.chosen[2] = 0
        #     combat.chosen[3] = 0
        #     combat.chosen[4] = 0
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
        pygame.display.update()  # 更新画面
    if(win == 1):
        print("you win")
        bgp = pygame.image.load("../Docs/images/win.PNG")
        Main.screen.fill((255, 255, 255))
        Main.screen.blit(pygame.transform.scale(bgp, (1120, 630)), (0, 0))
    else:
        print("you lost")
        bgp = pygame.image.load("../Docs/images/loss.PNG")
        Main.screen.fill((255, 255, 255))
        Main.screen.blit(pygame.transform.scale(bgp), (0, 0))
        pygame.display.update()
        sleep(2)
        print("you lost")
    return 0
